package com.example.xd.model_video.videoeditlib.editVideoPlay;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;


/**
 * Created by 半米阳光 on 2017/4/7.
 */

public class SPUtils {

    private static SPUtils instance;
    private static final String FILE_NAME = "NewCarPadLauncher";
    private static final String SAFE_FILE_NAME = "ColorshowStore";
    private SharedPreferences mSharedPreferences, mSafePreference;
    private SharedPreferences.Editor mEditor, mSafeEditor;
    private Gson gson;

    public synchronized static SPUtils getInstance() {
        if (instance == null)
            instance = new SPUtils();
        return instance;
    }

    public void init(Context context) {
        if (context == null)
            return;

        mSharedPreferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        mSafePreference = context.getSharedPreferences(SAFE_FILE_NAME, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
        mSafeEditor = mSafePreference.edit();
        gson = new Gson();
    }

    public void putBoolean(String key, boolean value) {
        mEditor.putBoolean(key, value);
        mEditor.commit();
    }

    public boolean getBoolean(String key, boolean defValue) {
        return mSharedPreferences.getBoolean(key, defValue);
    }

    public void putString(String key, String value) {
        mEditor.putString(key, value);
        mEditor.commit();
    }

    public String getString(String key, String defValue) {
        return mSharedPreferences.getString(key, defValue);
    }

    private void putStringInSafe(String key, String value) {
        mSafeEditor.putString(key, value);
        mSafeEditor.commit();
    }

    private String getStringInSafe(String key, String defValue) {
        return mSafePreference.getString(key, defValue);
    }

    public void putStringInEncryption(String key, String value) {
        putT(key, EncryptionUtil.encryptText(key, value));
    }

    public String getStringInEncryption(String key, String defValue) {
        Encryptor.ByteData data = getT(key, Encryptor.ByteData.class);
        if(data == null || data.getEncryption() == null || data.getIv() == null)
            return defValue;
        return EncryptionUtil.decryptText(key, data.getEncryption(), data.getIv());
    }

    public void putInt(String key, int value) {
        mEditor.putInt(key, value);
        mEditor.commit();
    }

    public int getInt(String key, int defValue) {
        return mSharedPreferences.getInt(key, defValue);
    }

    public <T> void putT(String key, T t){
        String data = gson.toJson(t);
        putStringInSafe(key, data);
    }

    public <T> T getT(String key, Class<T> tClass){
        String data = getStringInSafe(key, "");
        return gson.fromJson(data, tClass);
    }
}
